let app = getApp()
const db = wx.cloud.database({env: app.globalData.CLOUD_ENV})
const DBClassify = db.collection('db_classifys')
Page({
  data: {
    classifys: [],
    inpText: '',
    inpType: 'h5',
    index: 0,
    columns: [
      'h5', 
      'java', 
      '嵌入式', 
      'php', 
      'python',
      '网络工程'
    ],
  },

  bindPickerChange(e) {
    // console.log('picker发送选择改变，携带值为', e.detail.value)
    let index = e.detail.value;
    let type = this.data.columns[index];
    // type = type == "嵌入式"? 'qrs': type;
    // console.log({index,type})
    this.setData({
      index: index,
      inpType: type
    })
  },

  // 获取输入框的值
  addText(e) {
    // console.log(e)
    this.setData({
      inpText: e.detail.value
    })
  },

  // 添加题目分类的方法
  async addClassifyFn() {
    let that = this;
    let inpText = this.data.inpText;
    let type = this.data.inpType;
    let openid = wx.getStorageSync('openid');
    console.log({inpText,type})
    if (inpText == '' || type == '') {
      wx.showToast({
        title: '输入框不能为空。',
        icon: 'error'
      })
      return;
    }
    let option = {
      inpText
    }
    wx.cloud.callFunction({
      name: 'msgsec',
      data: {
        content: JSON.stringify(option),
        openid
      },
      success(res) {
        let {
          result: {
            errCode,
            errMsg
          }
        } = res;
        console.log('检测结果:', res); //  errCode == 0 表示文本正常
        if (errCode == 0) {
          // 添加分类
          DBClassify.where({
              text: inpText
            }).get()
            .then(
              content => {
                // 查询结果
                return content.data;
              }
            )
            .then(
              async (data) => {
                //根据查询结果判断是否存在当前分类
                if (data.length == 0) {
                  await DBClassify.add({
                      data: {
                        text: inpText,
                        total: 0,
                        type,
                        n: type,
                        openid: wx.getStorageSync('openid')
                      }
                    })
                    .then(
                      content => {
                        // console.log('x:',content)
                        if (content.errMsg == "collection.add:ok") {
                          wx.showToast({
                            title: '添加分类成功。',
                            icon: 'none'
                          })
                          // 重新获取列表
                          that.listClassifyFn();
                        } else {
                          wx.showToast({
                            title: '添加分类失败。',
                            icon: 'error'
                          })
                        }
                      }
                    )
                } else {
                  wx.showToast({
                    title: '当前分类已存在。',
                    icon: 'none'
                  })
                }
              }
            )
            .then(
              () => {
                // 重置输入框
                that.setData({
                  inpText: '',
                  inpTotal: ''
                })
              }
            )
        } else {
          if (errMsg != "openapi.security.msgSecCheck:ok") {
            wx.showToast({
              title: '您输入的内容包含敏感词哦。',
              icon: 'none'
            })
          } else {
            wx.showToast({
              title: `${errMsg},${errCode}`,
              icon: 'none'
            })
          }
        }
      }
    })
  },

  // 分类列表
  async listClassifyFn() {
    let that = this;
    let res = await DBClassify.where({}).count()
    let count = res.total;
    let all = [];
    for(let i = 0 ; i < count ; i+= 20){
        await DBClassify.where({}).skip(i).get()
        .then(
          content => {
            // console.log('3.0', content)
            let {data} = content;
            if(data.length!=0){
              all = all.concat(data)
            }
          }
        )
    }
    this.setData({
      classifys: all
    })
  },
  // 删除
  async removeFn(e) {
    let _id = e.currentTarget.dataset.id;
    let that = this;
    // console.log(_id);
    wx.showModal({
      title: '提示',
      content: '确定删除该分类吗?',
      complete: (res) => {
        if (res.cancel) {

        }
        if (res.confirm) {
          DBClassify.doc(_id).remove().then(
            content => {
              console.log('content', content)
              let {
                errMsg
              } = content;
              if (errMsg == "document.remove:ok") {
                let arr = that.data.classifys;
                let newArr = arr.filter(item => {
                  if (item._id != _id) {
                    return item
                  }
                })
                that.setData({
                  classifys: newArr
                })
              } else {
                wx.showToast({
                  title: '删除失败。',
                  icon: 'none'
                })
              }
            }
          )
        }
      }
    })

  },

  // 加载页面的回调函数
  onLoad() {
    this.listClassifyFn()
  }
})